// pages/main/main.js
const app = getApp()
const G = app.globalData
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		netgates: [],				// 所有网关  这里只保存名称和id即可，不存下一级的内容，即sensor_data, switchs, plantsummary，都不存多份
		idx: 0,					// 当前网关顺序（不是id)
		switchs_changeing: false,  // 防抖，当一个开关正在启闭时为真，为真时多次点击无效。
		loading: false
	},
	
	changenetgate: function(e){
		let that = this
		console.log(e)
		let idx = e.detail.current
		this.setData({
			idx: idx
		})
		app.getcuridxdatas(idx, () => {
			that.setData({
				netgates: G.datas.netgates,
				sensor_data: G.datas.netgates[idx].sensor_data,
				switchs: G.datas.netgates[idx].switchs,
				plantsummary: G.datas.netgates[idx].plantsummary
			})
		})
	},
	
	changeswitch: function(e){
		let that = this
		this.setData({
			switchs_changeing: true
		})
		// console.log(e)
		let id = e.currentTarget.dataset.id
		let switchname = e.currentTarget.dataset.name
		let status = e.detail.value ? 1 : 0 // 将status由ture/false转为1/0
		// console.log('id=', id, 'value=', value)
		app.get(app.urls.changetswitchstatus, {token: G.detail.token, id, status}, res => {
			console.log('changetswitchesstatus => ', res)
			wx.showToast({
				title: switchname + (res.data.status ? '已成功开启' : '已成功关闭'),
				icon: 'none'
			})
			that.setData({
				switchs_changeing: false
			})
		})
	},
	
	
	// setting: function(){
	// 	// 跳转到设置页
	// 	wx.navigateTo({
	// 		url: '/pages/setting/setting?netgate=' + this.data.netgate
	// 	})
	// },

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		let that = this
		console.log("now token is ", G.detail.token)
		let idx = that.data.idx
		app.getnetgates(() => {
			that.setData({
				netgates: G.datas.netgates
			})
			app.getcuridxdatas(idx, () => {
				// console.log('i reached here')
				that.setData({
					netgates: G.datas.netgates,
					loading: false
				})
			})
		})
		
	},
	

	
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		let that = this
		let idx = that.data.idx
		this.setData({
			loading: true
		})
		if (G.datas.netgates[idx] != undefined && G.datas.netgates[idx]['sensor_data'] != undefined){
			this.setData({
				netgates: G.datas.netgates,
				loading: false
			})	
		}
		
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	},
	
	/*
	
	
	
	
	
	*/
})